/*
 * file.c
 *
 */
/* Includes ------------------------------------------------------------------*/
#include "ff.h"  // 包含FatFS的头文件 
#include "app_file.h"
 #include "string.h"
#include "cJSON_Port.h"
/* Private typedef -----------------------------------------------------------*/

/* Private define ------------------------------------------------------------*/
const char *data = "Hello, World!";  // 要写入的数据 
/* Private macro -------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/
static FATFS fs;  // 文件系统对象 

static FILINFO files[8];
static uint8_t fileNums = 0;
static MemElements_t memObj;

static char version[32] = "V1.0.0";
static const char *pid  = "operation simulator";
static const char *vid  = "droidsurg";

static int itsHoleInserted[4] = {0,0,0,0};
static float lxEncodeData[2] = {0,0};
static char timestamp[32] = "0";
/* Exported variables --------------------------------------------------------*/

/* Private function prototypes -----------------------------------------------*/
static void scan_directory_for_json(const char* path);
static void parseJson(uint8_t *jsonBuffer, uint32_t length);
static cJSON * createDeviceInfo(void);
static cJSON * createData(void);
/* Private functions ---------------------------------------------------------*/
void scan_directory_for_json(const char* path) 
{
    FILINFO fno;
    DIR dir;
    FRESULT res;
 
    res = f_opendir(&dir, path);
    if (res != FR_OK) {
        printf("Failed to open directory %s\n", path);
        return;
    }

    while (1) {
 
        res = f_readdir(&dir, &fno);
        if (res != FR_OK || fno.fname[0]  == 0) break;  // 结束遍历 
 
        if ((fno.fattrib  & AM_DIR) == 0 && strcmp(fno.fname  + strlen(fno.fname)  - 5, ".json") == 0) {
            files[fileNums] = fno;
            fileNums++;
        }
        if(fileNums>8){
            break;
        }
    }
 
    f_closedir(&dir);
}
 

void parseJson(uint8_t *jsonBuffer, uint32_t length)
{
    // 实现JSON解析逻辑 
    // 例如，查找特定的键值对并提取数据 
    jsonBuffer[length]=0;
    cJSON *root = cJSON_Parse(jsonBuffer);
    while(root==NULL){

    }
    cJSON *plateHeightItem = cJSON_GetObjectItem(root,"plate_height");
    if(cJSON_IsNumber(plateHeightItem)){
        memObj.plate_height = plateHeightItem->valueint;
    }
    cJSON *dropIntervalItem = cJSON_GetObjectItem(root,"drop_interval");
    if(cJSON_IsNumber(dropIntervalItem)){
        memObj.drop_interval = dropIntervalItem->valueint;
    }

    cJSON *opModeItem = cJSON_GetObjectItem(root,"op_mode");
    if(cJSON_IsNumber(opModeItem)){
        memObj.op_mode = opModeItem->valueint;
    }
    cJSON *opSpeedItem = cJSON_GetObjectItem(root,"op_speed");
    if(cJSON_IsNumber(opSpeedItem)){
        memObj.op_speed = opSpeedItem->valueint;
    }

    cJSON *chanVolumnItem = cJSON_GetObjectItem(root,"channel_volume");
    if(cJSON_IsArray(chanVolumnItem)){
        int arr_size = cJSON_GetArraySize(chanVolumnItem);
        for(int i =0;i<arr_size;++i){
            cJSON * subItem = cJSON_GetArrayItem(chanVolumnItem,i);
            if(cJSON_IsNumber(subItem)){
                memObj.chanVolumn[i] = subItem->valueint;
            }

        }
    }

    cJSON *coeffItem = cJSON_GetObjectItem(root,"op_coefficient");
    if(cJSON_IsArray(coeffItem)){
        int arr_size = cJSON_GetArraySize(coeffItem);
        for(int i =0;i<arr_size;++i){
            cJSON * subItem = cJSON_GetArrayItem(coeffItem,i);
            if(cJSON_IsNumber(subItem)){
                memObj.op_coefficent[i] = subItem->valueint;
            }

        }
    }
}



/* Private functions ---------------------------------------------------------*/
cJSON * createDeviceInfo(void)
{
    cJSON *root = NULL;
    cJSON *data = NULL;
    root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "command", "getDeviceInfo");
    cJSON_AddNumberToObject(root, "errorCode", 0);
    cJSON_AddStringToObject(root, "errorMsg","");
//    time_t now;
//    int unixTimestamp = (int)time(&now);
//    sprintf(timestamp,"%d",unixTimestamp);
    cJSON_AddStringToObject(root, "timestamp",timestamp);
    cJSON_AddItemToObject(root, "data", data = cJSON_CreateObject());

    cJSON_AddStringToObject(data, "version", version);
    cJSON_AddStringToObject(data, "name", pid);
    cJSON_AddStringToObject(data, "model",vid);

    return root;
}

cJSON * createData(void)
{
    cJSON *root = NULL;
    cJSON *data = NULL;
    cJSON *deviceStatus = NULL;
    cJSON *sensors = NULL;

    root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "command", "getData");
    cJSON_AddNumberToObject(root, "errorCode", 0);
    cJSON_AddStringToObject(root, "errorMsg","");

//    time_t now;
//    int unixTimestamp = (int)time(&now);
//    sprintf(timestamp,"%d",unixTimestamp);
    cJSON_AddStringToObject(root, "timestamp",timestamp);
    cJSON_AddItemToObject(root, "data", data = cJSON_CreateObject());
    cJSON_AddItemToObject(data, "deviceStatus", deviceStatus = cJSON_CreateObject());
    cJSON_AddItemToObject(data, "sensors", sensors = cJSON_CreateObject());

    cJSON_AddNumberToObject(deviceStatus, "status", 1);
    cJSON_AddStringToObject(deviceStatus, "fault", "");
    cJSON_AddNumberToObject(deviceStatus, "organModel",1);


    cJSON_AddNumberToObject(sensors,"rightHand",1200);//右边关节镜角度编码器
    cJSON_AddNumberToObject(sensors,"rightBase",2400);//右边关节镜底盘角度编码器
    cJSON_AddNumberToObject(sensors,"leftBase",3600);//左边关节镜底盘角度编码器
    cJSON_AddNumberToObject(sensors,"leftHand",600);//左边关节镜角度编码器

    int32_t temp_count = 0;
    if(temp_count<0){
    	temp_count = 1000+temp_count;
    }else{
    	temp_count %= 1000;
    }
    cJSON_AddNumberToObject(sensors,"endoscopAngle",temp_count);//关节镜旋转角度
    cJSON_AddNumberToObject(sensors,"cutterAngle",4095);//剪刀工具张开角度
    cJSON_AddNumberToObject(sensors,"kneeAngle",lxEncodeData[0]);//膝关节旋转角度，其它关节为0//(lxEncodeData[0]+lxEncodeData[1])/2
//    cJSON_AddNumberToObject(sensors,"kneeAngle2",lxEncodeData[1]);//膝关节旋转角度，其它关节为0

    cJSON_AddBoolToObject(sensors,"leftCalibrator",true);
    cJSON_AddBoolToObject(sensors,"rightCalibrator",false);
    

    cJSON_AddItemToObject(sensors, "holes", cJSON_CreateIntArray(itsHoleInserted, 4));

    return root;
}
/* Exported functions --------------------------------------------------------*/
void vFILE_Init(void)
{
    vCJSON_Hooks_Init();
    FRESULT res = f_mount(&fs, "", 1);
    while (res!= FR_OK) {
    }
    FIL file;
    res = f_open(&file, "Hello.txt", FA_WRITE | FA_CREATE_ALWAYS);
    if (res == FR_OK) {
        res = f_write(&file, data, strlen(data), NULL);
        f_close(&file);
    }
    scan_directory_for_json("/");
    
    res = f_open(&file, files[0].fname, FA_READ);
    if (res == FR_OK) {
        uint8_t buffer[512];
        uint32_t readBytes;
        res = f_read(&file, buffer, sizeof(buffer), &readBytes);
        if (res == FR_OK) {
            // 处理读取到的JSON数据 
            parseJson(buffer, readBytes);
        }
        f_close(&file);
    }

}

void vFILE_GetPara(MemElements_pt obj)
{

}

//Save
void vFILE_SetPara(MemElements_pt obj)
{
    //以下是创建JSON对象的例子，可以根据存储对象创建JSON文件档，写入Flash等
    UNUSED(obj);
    cJSON * root = NULL;
    root = createData();
    char * json = cJSON_PrintUnformatted(root);
    cJSON_Delete(root);
    vPortFree(json);

}